# 月度比赛相关控制器
from app.models.monthly_competition import MonthlyCompetition, MonthlyCompetitionSignup
from app import db
from datetime import datetime

class MonthlyCompetitionController:
    @staticmethod
    def create_competition(name, description, start_date, end_date):
        comp = MonthlyCompetition(name=name, description=description, start_date=start_date, end_date=end_date)
        db.session.add(comp)
        db.session.commit()
        return comp

    @staticmethod
    def list_competitions():
        return MonthlyCompetition.query.order_by(MonthlyCompetition.start_date.desc()).all()

    @staticmethod
    def get_competition(comp_id):
        return MonthlyCompetition.query.get(comp_id)

    @staticmethod
    def signup_student(competition_id, student_id, group):
        from app.models.account import UserAccount
        exists = MonthlyCompetitionSignup.query.filter_by(competition_id=competition_id, student_id=student_id).first()
        if exists:
            return False, '您已报名该比赛'
        # 报名费 30 元
        signup_fee = 30.0
        user_account = UserAccount.query.filter_by(user_id=student_id).first()
        if not user_account or float(user_account.balance) < signup_fee:
            return False, '余额不足，请先充值后再报名'
        # 扣除报名费
        user_account.balance = float(user_account.balance) - signup_fee
        user_account.total_consumption = float(user_account.total_consumption) + signup_fee
        signup = MonthlyCompetitionSignup(competition_id=competition_id, student_id=student_id, group=group)
        db.session.add(signup)
        db.session.commit()
        return True, '报名成功，已扣除30元报名费'

    @staticmethod
    def get_signups(competition_id):
        return MonthlyCompetitionSignup.query.filter_by(competition_id=competition_id).all()
